import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource } from 'typeorm';
import { RechargeRule } from './entities/recharge-rule.entity';
import { UserRecharge, PaymentStatus } from './entities/user-recharge.entity';
import { CreateRechargeRuleDto } from './dto/create-recharge-rule.dto';
import { InitiateRechargeDto } from './dto/initiate-recharge.dto';
import { PaymentCallbackDto } from './dto/payment-callback.dto';
import { WalletService } from '../wallet/wallet.service';

/**
 * 充值服务
 */
@Injectable()
export class RechargeService {
  constructor(
    @InjectRepository(RechargeRule)
    private readonly rechargeRuleRepository: Repository<RechargeRule>,
    @InjectRepository(UserRecharge)
    private readonly userRechargeRepository: Repository<UserRecharge>,
    private readonly walletService: WalletService,
    private readonly dataSource: DataSource,
  ) {}

  /**
   * 创建充值规则
   */
  async createRule(createDto: CreateRechargeRuleDto): Promise<RechargeRule> {
    const rule = this.rechargeRuleRepository.create({
      ...createDto,
      isActive: createDto.isActive !== undefined ? createDto.isActive : true,
    });
    return await this.rechargeRuleRepository.save(rule);
  }

  /**
   * 获取所有充值规则
   */
  async getRules(): Promise<RechargeRule[]> {
    return await this.rechargeRuleRepository.find({
      where: { isActive: true },
      order: { rechargeAmount: 'ASC' },
    });
  }

  /**
   * 获取所有充值规则（管理员）
   */
  async getAllRules(): Promise<RechargeRule[]> {
    return await this.rechargeRuleRepository.find({
      order: { rechargeAmount: 'ASC' },
    });
  }

  /**
   * 根据充值金额获取奖励代金券
   */
  async getBonusVoucher(amount: number): Promise<number> {
    const rule = await this.rechargeRuleRepository.findOne({
      where: { rechargeAmount: amount, isActive: true },
    });
    return rule ? rule.bonusVoucher : 0;
  }

  /**
   * 发起充值
   */
  async initiateRecharge(userId: number, initiateDto: InitiateRechargeDto): Promise<UserRecharge> {
    const { amount, paymentChannel } = initiateDto;
    
    // 获取奖励代金券金额
    const bonusVoucher = await this.getBonusVoucher(amount);
    
    // 生成订单号
    const orderNo = this.generateOrderNo();
    
    const recharge = this.userRechargeRepository.create({
      userId,
      amount,
      bonusVoucher,
      paymentChannel,
      orderNo,
      paymentStatus: PaymentStatus.PENDING,
    });
    
    return await this.userRechargeRepository.save(recharge);
  }

  /**
   * 处理支付回调
   */
  async handlePaymentCallback(callbackDto: PaymentCallbackDto): Promise<UserRecharge> {
    const { orderNo, thirdPartyOrderNo, paymentStatus, failureReason } = callbackDto;
    
    // TODO: 验证签名
    // this.verifySignature(callbackDto);
    
    const recharge = await this.userRechargeRepository.findOne({
      where: { orderNo },
    });
    
    if (!recharge) {
      throw new NotFoundException(`订单 ${orderNo} 不存在`);
    }
    
    if (recharge.paymentStatus !== PaymentStatus.PENDING) {
      throw new BadRequestException(`订单 ${orderNo} 状态异常`);
    }
    
    return await this.dataSource.transaction(async (manager) => {
      // 更新充值记录
      recharge.thirdPartyOrderNo = thirdPartyOrderNo;
      recharge.paymentStatus = paymentStatus;
      recharge.failureReason = failureReason;
      
      if (paymentStatus === PaymentStatus.PAID) {
        recharge.paidAt = new Date();
        
        // 增加用户余额
        await this.walletService.addBalance(recharge.userId, recharge.amount);
        
        // 增加代金券余额
        if (recharge.bonusVoucher > 0) {
          await this.walletService.addVoucherBalance(recharge.userId, recharge.bonusVoucher);
        }
      }
      
      return await manager.save(UserRecharge, recharge);
    });
  }

  /**
   * 获取用户充值记录
   */
  async getUserRechargeHistory(userId: number, page = 1, limit = 10): Promise<{
    data: UserRecharge[];
    total: number;
    page: number;
    limit: number;
  }> {
    const [data, total] = await this.userRechargeRepository.findAndCount({
      where: { userId },
      order: { createdAt: 'DESC' },
      skip: (page - 1) * limit,
      take: limit,
    });
    
    return { data, total, page, limit };
  }

  /**
   * 生成订单号
   */
  private generateOrderNo(): string {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    return `ORDER_${timestamp}_${random}`;
  }

  /**
   * 验证签名（待实现）
   */
  private verifySignature(callbackDto: PaymentCallbackDto): boolean {
    // TODO: 实现签名验证逻辑
    return true;
  }
}